﻿using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using BusinessLogicLayer;
using DataAccessLayer;
using Autofac.Integration.Mvc;
using System.Web.Mvc;
using IBusinessLogicLayer;
using IDataAccessLayer;

namespace MVC
{
    public static class AutofacExt
    {
        private static IContainer _container;

        public static void InitAutofac()
        {
            var builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof (BaseDal<>)).As(typeof (IBaseDal<>));
            builder.RegisterGeneric(typeof (BaseBll<>)).As(typeof (IBaseBll<>));
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(BaseDal<>)))
                .Where(u => u.Name.EndsWith("Dal"))
                .AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(Assembly.GetAssembly(typeof(BaseBll<>)))
               .Where(u => u.Name.EndsWith("Bll"))
               .AsImplementedInterfaces();
            // Register your MVC controllers. (MvcApplication is the name of
            // the class in Global.asax.)
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // OPTIONAL: Register model binders that require DI.
            builder.RegisterModelBinders(typeof(MvcApplication).Assembly);
            builder.RegisterModelBinderProvider();

            // OPTIONAL: Register web abstractions like HttpContextBase.
            builder.RegisterModule<AutofacWebTypesModule>();

            // OPTIONAL: Enable property injection in view pages.
            builder.RegisterSource(new ViewRegistrationSource());

            // OPTIONAL: Enable property injection into action filters.
            builder.RegisterFilterProvider();

            // OPTIONAL: Enable action method parameter injection (RARE).
            //builder.InjectActionInvoker();

            // Set the dependency resolver to be Autofac.
            _container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(_container));
        }

        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }
    }
}